import ThemeToggle from '@/components/ThemeToggle';
import { defaultSettings } from '@/config/defaultSettings';
import { getCurrentTheme, getSavedTheme, type ThemeKey } from '@/config/themeConfig';
import { ProLayout } from '@ant-design/pro-components';
import type { MenuDataItem, ProLayoutProps } from '@ant-design/pro-layout';
import { getLocale, history, Link, Outlet, useLocation, useModel } from '@umijs/max';
import type { ThemeConfig } from 'antd';
import { ConfigProvider } from 'antd';
import en from 'antd/locale/en_US';
import zhCN from 'antd/locale/zh_CN';
import zhTW from 'antd/locale/zh_TW';
import 'dayjs/locale/en';
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/zh-tw';
import _ from 'lodash';
import React, { useCallback, useEffect, useState } from 'react';
import LanguageBar from './LanguageBar';
import LogoBar from './LogoBar';
import UserBar from './UserBar';
// import defaultProps from './defaultProps';

// antd国际化枚举
const languagePackage: any = {
  'en-US': en,
  'zh-CN': zhCN,
  'zh-TW': zhTW,
};

const BasicLayout: React.FC<ProLayoutProps> = () => {
  const locale = languagePackage[getLocale()];
  const location = useLocation();
  const { initialState } = useModel('@@initialState') as any;

  // 主题状态
  const [currentThemeConfig, setCurrentThemeConfig] = useState(getCurrentTheme('blue-light'));

  // 初始化主题
  useEffect(() => {
    const savedTheme = getSavedTheme();
    const themeConfig = getCurrentTheme(savedTheme);
    setCurrentThemeConfig(themeConfig);
  }, []);

  // 主题切换处理
  const handleThemeChange = useCallback((themeKey: ThemeKey) => {
    const themeConfig = getCurrentTheme(themeKey);
    setCurrentThemeConfig(themeConfig);
  }, []);

  // 用于监听路由变化，若路由地址不在选单接口数据内，则跳到404页面
  useEffect(() => {
    if (_.isEmpty(initialState?.menuData)) return;

    const currentPath = location.pathname;

    // 白名单路径（不需要权限校验）
    const whiteList = ['/', '/welcome', '/404'];
    if (whiteList.includes(currentPath)) return;

    // 使用reduce递归收集所有菜单路径
    const getAllMenuPaths = (menus: any[]): string[] => {
      return menus.reduce((paths: string[], item: any) => {
        if (item.resourceUrl) {
          paths.push(item.resourceUrl);
        }
        if (item.children && item.children.length > 0) {
          paths.push(...getAllMenuPaths(item.children));
        }
        return paths;
      }, []);
    };

    const allMenuPaths = getAllMenuPaths(initialState.menuData);
    if (!allMenuPaths.includes(currentPath)) {
      console.warn(`Path ${currentPath} not found in menu data, redirecting to 404`);
      history.push('/404');
    }
  }, [location.pathname, initialState?.menuData]);

  // 处理选单结构
  const loopMenuItem = (menus: MenuDataItem[]): MenuDataItem[] => {
    return menus.map((item) => {
      const menuItem: MenuDataItem = {
        ...item,
        path: item.resourceUrl,
        name: item.resourceName,
        key: item.id.toString() || item.resourceUrl, // 使用路径作为key，这样ProLayout能正确匹配
      };

      if (item.children && item.children.length > 0) {
        menuItem.children = loopMenuItem(item.children);
      }

      return menuItem;
    });
  };

  const avatarRender = () => <UserBar />;
  const actionsRender = () => [
    <ThemeToggle key="theme" onChange={handleThemeChange} />,
    <LanguageBar key="language" />,
  ];

  const logoRender = () => <LogoBar />;

  return (
    <ConfigProvider locale={locale} theme={currentThemeConfig as ThemeConfig}>
      <ProLayout
        token={currentThemeConfig.token}
        location={location}
        avatarProps={{ render: (props, dom) => avatarRender() }}
        actionsRender={(props) => actionsRender()}
        logo={logoRender()}
        title={false}
        menu={{
          request: async () => {
            if (!initialState?.menuData) return [];
            return loopMenuItem(initialState.menuData);
          },
        }}
        menuItemRender={(menuItemProps, defaultDom) => {
          const { path, isUrl, children } = menuItemProps;
          if (isUrl || (children && children.length) || !path) {
            return defaultDom;
          }
          return <Link to={path}>{defaultDom}</Link>;
        }}
        {...defaultSettings}
        style={{
          transition: 'all 0.3s ease',
        }}
      >
        {/* 页面标签栏 */}
        {/* <PageTabs /> */}

        <div>
          <Outlet />
        </div>
      </ProLayout>
    </ConfigProvider>
  );
};

export default BasicLayout;
